const KEY = 'rf_mySearch';

Page({
  data: {
    history: [],
    hot: [],
    keyword: '',
    showActionSheet: false,
    tips: "确认清空搜索历史吗？"
  },
  onLoad: async function (options) {
    let res = await wx.util.request('common.config', {
      query: 'field=hot_search_default,hot_search_list'
    });
    this.setData({
      default: res.hot_search_default,
      hot: res.hot_search_list.split(',')
    });
  },
  onShow: function () {
    this.setData({
      history: wx.getStorageSync(KEY)
    });
  },
  back: function () {
    wx.navigateBack();
  },
  input: function (e) {
    this.setData({
      keyword: wx.util.trim(e.detail.value)
    })
  },
  clearKeyword: function () {
    this.setData({
      keyword: ''
    });
  },
  search: function (e) {
    let keyword = '',
        pages = getCurrentPages(),
        prevPage = pages[pages.length - 2];

    if (e.type == 'click') {
      keyword = e.currentTarget.dataset.keyword;
    } else if (e.type == 'confirm') {
      keyword = e.detail.value || this.data.default;
    }
    this.setData({
      keyword: keyword
    });
    this.updateHistory(keyword);

    if (prevPage.route.indexOf('product/index') > -1) {
      prevPage.setData({
        keyword: keyword
      });
      wx.navigateBack();
      return;
    }
    wx.navigateTo({
      url: `../product/index?keyword=${keyword}`,
    });
  },
  updateHistory: function (keyword) {
    let data = this.data,
        oriHistory = data.history || [],
        newHistory = [keyword];

    if (keyword != '') {
      if (oriHistory.length > 0) {
        for (let i in oriHistory) {
          if (newHistory.length >= 10) break;
          if (newHistory.indexOf(oriHistory[i]) < 0) {
            newHistory.push(oriHistory[i]);
          }
        }
      }
      
      wx.setStorageSync(KEY, newHistory);
    }
  },
  closeActionSheet: function () {
    this.setData({
      showActionSheet: false
    })
  },
  openActionSheet: function () {
    this.setData({
      showActionSheet: true
    })
  },
  removeHistory: function (e) {
    if (e.detail.index == 0) {
      wx.removeStorageSync(KEY);
      this.setData({
        history: []
      });
    }
    this.closeActionSheet();
  }
})